/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.cs576.playerWithHyperLink;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;

/**
 *
 * @author Ludo
 */
public class PrimaryVideo extends JPanel{
    private BufferedImage image;
    private int width = 352;
    private int height = 288;
    private byte[] videoBytes; //the bytes that will currently be shown on the panel
    private int totalFrames;
    
	private static boolean isPause = false;
	private static boolean isStop = false;
	private static boolean isPlayAfterStop = false;
	private int currentPlayingFrame = 0;
	private int drawX = 0;
	private int drawY = 0;
	private int drawWidth = 0;
	private int drawHeight = 0;
	
	
	ReadMetaFile Reader;
	ArrayList AllRects = new ArrayList();
	ArrayList AllStartandEndFrameNum = new ArrayList();
	ArrayList Rect = new ArrayList();
	int GDrawingRects[][];
  
	
	
	
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        
			


        if (image != null) {
            //g.clearRect(0, 0, width, height);
            g.drawImage(image, 0, 0, null);
            g.setColor(Color.yellow);
            
            for(int i = 0 ; i < GDrawingRects.length; i++)
            	g.drawRect(GDrawingRects[i][0], GDrawingRects[i][1], GDrawingRects[i][2], GDrawingRects[i][3]);

    		
            g.dispose();
        }

    }
    
    
    
    
    public int getcurrentPlayingFrame()
    {
    	return currentPlayingFrame;
    }
    
	
	public boolean getisPlayAfterStop()
	{
		return isPlayAfterStop;
	}
	
	public void setisPlayAfterStop()
	{
		isPlayAfterStop = true;
	}
	
	public void setNotPlayAfterStop()
	{
		isPlayAfterStop = false;
	}
	
	public boolean getIsStop()
	{
		return isStop;
	}
	
	public void setIsStop()
	{
		isStop = true;
	}
	
	public void setNotStop()
	{
		isStop = false;
	}
	
	public void setIsPause()
	{
		isPause = true;
	}
	
	public void setNotPause()
	{
		isPause = false;
	}
	
	public boolean getisPause()
	{
		return isPause;	
	}
	
	public void SetUpGUI()
	{
    	this.setPreferredSize(new java.awt.Dimension(352, 288));
	    JFrame NewFrame = new JFrame("HyperLink Player");
	    PlayerPanel2 playerPanel = new PlayerPanel2();
	    NewFrame.setContentPane(playerPanel.CreatLayOut(this));
	    NewFrame.setSize(800, 600);
	    NewFrame.setVisible(true);
	}
    
    public void playVideo() throws FileNotFoundException
    {
    	
		Reader = new ReadMetaFile();
		AllRects = Reader.getAllRectsToDraw();
		AllStartandEndFrameNum = Reader.getAllStartandEndFrameNum();
		System.out.println("Reader.getAllRectsToDraw():" + Reader.getAllRectsToDraw());
		System.out.println("Reader.getAllStartandEndFrameNum():" + Reader.getAllStartandEndFrameNum());
		GDrawingRects = new int[AllRects.size()][4];
    	
		File file = new File("vdo5.rgb");
	    byte[] primaryVideo = getVideoFile(file);
    	this.setBytes(primaryVideo);
    	ArrayList Rect = new ArrayList();
    	ArrayList pointsForDrawingRects = new ArrayList();
    	
    	SetUpGUI();

    	
    	//while(true)
    	//{
	    for(int i = 0 ; i < this.getTotalNumberOfFrames() ; i++)
	    {
	    	setFrame(i);
	    	currentPlayingFrame = i;
	    	
	    	
	    	   for(int j = 0 ; j < AllRects.size() ; j++)
	    	   {
	    		   ArrayList startandEndFrame = (ArrayList) AllStartandEndFrameNum.get(j);
	    		   int startFrame = (int) startandEndFrame.get(0);
	    		   int endFrame = (int) startandEndFrame.get(1);
	    		   if( (getcurrentPlayingFrame() >= startFrame ) && (getcurrentPlayingFrame() <= endFrame) )
	    		   {
	    			    ArrayList Rectangle = (ArrayList) AllRects.get(j); 
	    			    
	            		pointsForDrawingRects = (ArrayList) Rectangle.get(getcurrentPlayingFrame()-93);
	            		
	            		GDrawingRects[j][0] = (int) pointsForDrawingRects.get(0);
	            		GDrawingRects[j][1] = (int) pointsForDrawingRects.get(1);
	            		GDrawingRects[j][2] = (int) pointsForDrawingRects.get(2);
	            		GDrawingRects[j][3] = (int) pointsForDrawingRects.get(3);
	            		System.out.println("FrameNumber" + getcurrentPlayingFrame());
	            		System.out.println((int) pointsForDrawingRects.get(0) +"_"+ (int) pointsForDrawingRects.get(1) +"_"+ (int) pointsForDrawingRects.get(2) +"_"+ (int) pointsForDrawingRects.get(3));


	    		   }
	    		   else
	    		   {
	            		GDrawingRects[j][0] = 0;
	            		GDrawingRects[j][1] = 0;
	            		GDrawingRects[j][2] = 0;
	            		GDrawingRects[j][3] = 0;
	    		   }
	    	   }
	    	
	    	
	    	
	    	
	    	
	    	
			while(getisPause() || getIsStop())
			{
				System.out.println("PlayinggetIsPause(): " + this.getisPause());				
			}
			
			
			if(getisPlayAfterStop() == true )
			{
				i = 0 ;
				setNotPlayAfterStop();
				
			}
	    	
	    	try {
				Thread.sleep((long) (1.0 / Integer.parseInt("2")) * 1000 );
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	
	    	
	    }
	    //}
    }
    

    
	   private byte[] getVideoFile(File file) {
	        byte[] bytes = null;
	        try {
	            InputStream is = new FileInputStream(file);
	            long len = file.length();
	            try {
	                bytes = new byte[(int) len];
	                int offset = 0;
	                int numRead = 0;
	                while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
	                    offset += numRead;
	                }

	                is.close();
	            } catch (OutOfMemoryError e) {
	          
	            }
	        } catch (FileNotFoundException e) {
	            System.out.println("File not found");
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        return bytes;
	    }
    
   
        /**
     * Setting byte array of video to be displayed
     *
     * @param bytes
     */
    public void setBytes(byte[] bytes) {
        videoBytes = bytes;
        totalFrames = videoBytes.length/height/width/3-1;
        initImage();
    }
    
    public int getTotalNumberOfFrames(){
        if(videoBytes != null){
            return totalFrames;
        }else{
            return 0;
        }
    }
    
    public boolean isVideoSet(){
        if (videoBytes == null){
            return false;
        }else{
            return true;
        }
    }
    
    public void setFrame(int frameNum){
        image = getFrame(frameNum);
        this.repaint();
    }

    /**
     * Picks frame to display of current video in jPanel. Make sure videoBytes
     * is not null.
     */
    private BufferedImage getFrame(int frame) {
    	

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        if (videoBytes == null) {
            System.out.println("video bytes is null.");
            return img;
        }
        int ind = frame * height * width * 3;
        //while(true)
        //{
        for (int y = 0; y < height; y++) {

            for (int x = 0; x < width; x++) {

                byte a = 0;
                byte r = videoBytes[ind];
                byte g = videoBytes[ind + height * width];
                byte b = videoBytes[ind + height * width * 2];

                int pix = 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
                //int pix = ((a << 24) + (r << 16) + (g << 8) + b);
                img.setRGB(x, y, pix);
                ind++;

            }

        }
        //}
        return img;
    }

    private void initImage() {
        image = getFrame(0);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
    }
}
